package com.foot.travel.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.foot.travel.R;
import com.foot.travel.event.NetRefreshEvent;
import com.foot.travel.viewholder.GalleryItemViewHolder;
import com.koalac.ironman.common.adapter.CommonAdapter;
import com.koalac.ironman.common.module.ModuleActivity;
import com.koalac.ironman.net.MyRequest;
import com.koalac.ironman.net.ResponseCallback;
import com.koalac.ironman.net.pojo.request.GetGalleryHomePicture;
import com.koalac.ironman.net.pojo.request.GetGalleryList;
import com.koalac.ironman.net.pojo.response.GalleryItem;
import com.koalac.ironman.net.pojo.response.Picture;
import com.koalac.ironman.net.pojo.response.Response;
import com.koalac.ironman.util.ScreenInfoUtil;
import com.koalac.ironman.util.WeakHandler;
import com.koalac.ironman.viewhelper.ViewInject;
import com.koalac.ironman.widget.ImageLoadAgreement.ImageType;
import com.koalac.ironman.widget.LifeqImageView;
import com.koalac.ironman.widget.PullToRefreshView;
import com.koalac.ironman.widget.PullToRefreshView.OnFooterRefreshListener;
import com.koalac.ironman.widget.PullToRefreshView.OnHeaderRefreshListener;
import com.koalac.ironman.widget.ScrollViewPager;
import com.shizhefei.view.indicator.FixedIndicatorView;
import com.shizhefei.view.indicator.IndicatorViewPager;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorPagerAdapter;
import com.shizhefei.view.indicator.IndicatorViewPager.IndicatorViewPagerAdapter;
import com.squareup.otto.Subscribe;

public class MostBeautifulPhotoActivity extends ModuleActivity
		implements OnHeaderRefreshListener, OnFooterRefreshListener {

	@ViewInject(id = R.id.beautiful_photo_container)
	PullToRefreshView mBeautifulPhotoContainer;
	@ViewInject(id = R.id.beautiful_photo_listview)
	ListView mBeautifulPhotoListview;
	LinearLayout mGuideIndicatorLayout;

	public CommonAdapter<GalleryItem> mGalleryItemAdapter;
	private GetGalleryList mGetGalleryList;
	public List<GalleryItem> mGalleryItemList = new ArrayList<GalleryItem>();

	private LayoutInflater mLayoutInflater;
	ScrollViewPager mGuideViewPager;
	private ArrayList<String> mCoverImageUrlList;
	public static final int REQUEST_PUBLISH_PHOTO_CODE = 1 << 0;
	public static final String GALLRY_ITEM = "gallry_data";

	private ScheduledExecutorService mScheduledExecutorService;
	private int mCurrentItem;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setNavigationTitle("最美旅图");
		setBackButtonVisibility(true);
		setEditTravelPhotoVisibility(true);
		mEditTravelPhotoView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MostBeautifulPhotoActivity.this, PublishPhotoActivity.class);
				startActivityForResult(intent, REQUEST_PUBLISH_PHOTO_CODE);
			}
		});
		mBeautifulPhotoContainer.setOnHeaderRefreshListener(MostBeautifulPhotoActivity.this);
		mBeautifulPhotoContainer.setOnFooterRefreshListener(MostBeautifulPhotoActivity.this);
		mLayoutInflater = LayoutInflater.from(MostBeautifulPhotoActivity.this);
		getGalleryHomePicture();
		getGalleryList();
	}

	@Override
	protected void onResume() {
		super.onResume();
		super.onStart();
		mScheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		// 每隔2秒钟切换一张图片
		mScheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 3, 3, TimeUnit.SECONDS);
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (!mScheduledExecutorService.isShutdown()) {
			mScheduledExecutorService.shutdown();
		}
	}

	// 切换图片
	private class ViewPagerTask implements Runnable {

		@Override
		public void run() {
			mCurrentItem = mGuideViewPager.getCurrentItem();
			mCurrentItem++;
			// 更新界面
			handler.obtainMessage().sendToTarget();
		}
	}

	private WeakHandler<MostBeautifulPhotoActivity> handler = new WeakHandler<MostBeautifulPhotoActivity>(
			MostBeautifulPhotoActivity.this) {

		@Override
		protected void processMessage(MostBeautifulPhotoActivity activity, Message msg) {
			// 设置当前页面
			mGuideViewPager.setCurrentItem(mCurrentItem, true);
		}
	};

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK && requestCode == REQUEST_PUBLISH_PHOTO_CODE) {
			GalleryItem galleryItem = (GalleryItem) data.getSerializableExtra(GALLRY_ITEM);
			mGalleryItemList.add(0, galleryItem);
			mGalleryItemAdapter.notifyDataSetChanged();
		}
	}

	private void getGalleryList() {
		mGetGalleryList = new GetGalleryList();
		mGalleryItemAdapter = new CommonAdapter<GalleryItem>(GalleryItemViewHolder.class, mGalleryItemList,
				MostBeautifulPhotoActivity.this, R.layout.gallery_photo_item);
		mBeautifulPhotoListview.setAdapter(mGalleryItemAdapter);
		loadData(GalleryItem.class, LoadState.init, mGetGalleryList, mBeautifulPhotoContainer, mGalleryItemAdapter,
				mGalleryItemList);
	}

	private void getGalleryHomePicture() {
		View galleryPicturesView = mLayoutInflater.inflate(R.layout.shuffling_figure_layout, null);
		mBeautifulPhotoListview.addHeaderView(galleryPicturesView);
		mGuideViewPager = (ScrollViewPager) galleryPicturesView.findViewById(R.id.guide_viewPager);
		mGuideIndicatorLayout = (LinearLayout) galleryPicturesView.findViewById(R.id.guide_indicator_layout);
		setGuideViewPagerHeight();

		GetGalleryHomePicture getGalleryHomePicture = new GetGalleryHomePicture();
		MyRequest.request(MostBeautifulPhotoActivity.this, getGalleryHomePicture, new ResponseCallback() {

			@SuppressWarnings("deprecation")
			@Override
			public void process(boolean result, Context context, Response data, String msg) {
				if (result) {
					List<Picture> pictureList = data.getList(Picture.class);

					mCoverImageUrlList = new ArrayList<String>();
					for (Picture picture : pictureList) {
						mCoverImageUrlList.add(picture.getPicurl());
					}
					mGuideViewPager.setAdapter(pagerAdapter);
					mGuideViewPager.setCurrentItem(mCoverImageUrlList.size() * 100, false);
					pagerAdapter.notifyDataSetChanged();
					setUpGuideIndicatorLayout(mGuideIndicatorLayout);
					mGuideViewPager.setOnPageChangeListener(new OnPageChangeListener() {

						@Override
						public void onPageSelected(int position) {
							int size = mGuideIndicatorLayout.getChildCount();
							for (int i = 0; i < size; i++) {
								View indicator = mGuideIndicatorLayout.getChildAt(i);
								indicator.setSelected(false);
							}
							mGuideIndicatorLayout.getChildAt(position % mCoverImageUrlList.size()).setSelected(true);
							;
						}

						@Override
						public void onPageScrolled(int arg0, float arg1, int arg2) {

						}

						@Override
						public void onPageScrollStateChanged(int arg0) {

						}
					});
				}
			}
		});
	}

	PagerAdapter pagerAdapter = new PagerAdapter() {

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		public Object instantiateItem(ViewGroup container, int position) {
			View convertView = mLayoutInflater.inflate(R.layout.image_home_layout, container, false);
			((LifeqImageView) convertView.findViewById(R.id.image)).loadFile(
					mCoverImageUrlList.get(position % mCoverImageUrlList.size()), ImageType.SourceImage, null, null);
			container.addView(convertView);
			return convertView;
		}

		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;
		}
	};

	private void setUpGuideIndicatorLayout(LinearLayout guideIndicatorLayout) {
		int indicatorSize = ScreenInfoUtil.dp2px(MostBeautifulPhotoActivity.this, 10);
		for (int i = 0; i < mCoverImageUrlList.size(); i++) {
			View indicator = mLayoutInflater.inflate(R.layout.tab_guide, null);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(indicatorSize, indicatorSize);
			lp.setMargins(0, 0, indicatorSize, 0);
			indicator.setLayoutParams(lp);
			guideIndicatorLayout.addView(indicator);
		}
	}

	private void setGuideViewPagerHeight() {
		int height = ScreenInfoUtil.getScreenWidth(MostBeautifulPhotoActivity.this) / 2;
		RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) mGuideViewPager
				.getLayoutParams();
		layoutParams.height = height;
		mGuideViewPager.setLayoutParams(layoutParams);
	}

	@Override
	protected void initLayout(ViewGroup rootContentView) {
		addContentView(R.layout.activity_most_beautiful_photo);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		loadData(GalleryItem.class, LoadState.refresh, mGetGalleryList, mBeautifulPhotoContainer, mGalleryItemAdapter,
				mGalleryItemList);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		loadData(GalleryItem.class, LoadState.more, mGetGalleryList, mBeautifulPhotoContainer, mGalleryItemAdapter,
				mGalleryItemList);
	}
	
	@Subscribe
	    public void onRefresh(NetRefreshEvent netRefreshEvent) {
		setNetworkVisibility(false);
		getGalleryHomePicture();
		getGalleryList();
	    }

}
